package com.janlei.clone;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Objects;

/**
 * objectClone
 */
public class ObjectClone implements Cloneable, Serializable {

    private final Integer id;

    private final String name;

    public ObjectClone(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    /**
     * deepClone 需要实现序列化接口
     *
     * @return
     */
    public Object deepClone() throws IOException, ClassNotFoundException {
        // 将对象写入流内
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this);

        // 从流内读出对象
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
                bos.toByteArray()));
        return ois.readObject();
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }


    //**********equals and hashcode ****************************
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ObjectClone that = (ObjectClone) o;

        if (!Objects.equals(id, that.id)) return false;
        return Objects.equals(name, that.name);
    }

    @Override
    public int hashCode() {
        int result = id != null ? id.hashCode() : 0;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "ObjectClone{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
